import { onBeforeUnmount, computed, ref, shallowRef, nextTick } from 'vue'
import { OssUploadFile } from 'utils/oss.js'

// import { DomEditor } from '@wangeditor/editor'
import { Boot } from '@wangeditor/editor'

import mentionModule from '@wangeditor/plugin-mention'

// 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
Boot.registerModule(mentionModule)

import { staff_list_post_ } from 'server/apis/1836.js'

// 编辑器实例，必须用 shallowRef
export const editorRef = shallowRef()

export const modelValue = ref(null)

export const init = function (props) {
  modelValue.value = props.value
  /**
   * 处理富文本样式
   */
  const styles = computed(() => {
    const style = {
      background: '#fff',
      paddingBottom: '30px'
    }
    if (props.minHeight) {
      style.minHeight = `${props.minHeight}px`
    }
    if (props.height) {
      style.height = `${props.height}px`
    }
    return style
  })
  const toolbarConfig = {
    excludeKeys: [
      'lineHeight',
      '|',
      'group-video',
      'todo',
      'insertTable',
      'codeBlock',
      'divider',
      'undo',
      'redo',
      'fullScreen',
      'group-more-style',
      'insertImage'
    ]
  }
  /**
   * 编辑器的配置
   */
  const editorConfig = ref({
    placeholder: '请输入内容...',
    readOnly: props.readOnly || false,
    MENU_CONF: {},
    EXTEND_CONF: {
      mentionConfig: {
        showModal() {
          // userList.value = memberList.value
          // memberVisible.value = true
        },
        hideModal() {
          // memberVisible.value = false
        }
      }
    }
  })
  const handleCreated = editor => {
    editorRef.value = editor // 记录 editor 实例，重要！
  }

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    // const editor = editorRef.value
    // if (editor == null) return
    // editor.destroy()
  })
  return {
    toolbarConfig,
    styles,
    editorConfig,
    handleCreated
  }
}

/**
 * 处理图片上传
 * @returns
 */
export const handlerImageUpload = function (props, editorConfig) {
  editorConfig.value['MENU_CONF']['uploadImage'] = {
    maxFileSize: 20 * 1024 * 1024, // 1M
    allowedFileTypes: ['image/*'],
    // 自定义插入图片
    customUpload(file, insertFn) {
      uploadFile(file, insertFn)
    }
  }
  const customPaste = (editor, event) => {
    if (
      event.clipboardData &&
      event.clipboardData.files &&
      event.clipboardData.files.length
    ) {
      handlerChange(event.clipboardData.files)
    }
    const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
    if (text) {
      editor.insertText(text)
    }

    // 阻止默认的粘贴行为
    event.preventDefault()
    return false
  }

  const insertImage = (url, alt, href) => {
    const node = {
      type: 'image',
      src: url,
      alt,
      href,
      children: [{ text: '' }]
    }
    editorRef.value.insertNode(node)
  }

  const getOssRegion = () => {
    if (process.env.VUE_APP_MODE === 'production') {
      return 'oss-accelerate'
    }
    return 'oss-cn-hangzhou'
  }
  const replaceURL = url => {
    if (process.env.VUE_APP_MODE === 'production') {
      return url.replace(
        'cs-scm.oss-accelerate.aliyuncs.com',
        'oss-scm-prod.kapeixi.cn'
      )
    }
    return url
  }
  const uploadFile = async file => {
    const region = getOssRegion()

    const oss = OssUploadFile.getInstance(region)

    const result = await oss.put(file).catch(() => {
      return null
    })
    const url = replaceURL(result.res.requestUrls[0])
    insertImage(url, '', url)
  }
  const handlerChange = files => {
    files.forEach(file => {
      uploadFile(file)
    })
  }

  return {
    customPaste
  }
}

/**
 * 处理富文本@用户
 * @returns
 */
export const handlerAtUser = function () {
  const { staffListData } = staff_list_post_({})
  const memberVisible = ref(false)

  const userList = ref([])

  const searchValue = ref('')

  /**
   * 插入@用户
   * @param {*} user
   */
  const insertTagUser = user => {
    const mentionNode = {
      type: 'mention', // 必须是 'mention'
      value: user.fullName,
      info: { id: user.userId },
      children: [{ text: '' }] // 必须有一个空 text 作为 children
    }
    const editor = editorRef.value
    if (editor) {
      editor.restoreSelection() // 恢复选区
      editor.deleteBackward('character') // 删除 '@'
      if (searchValue.value && searchValue.value.length > 0) {
        searchValue.value.split('').map(() => {
          editor.deleteBackward('character') // 删除 '@'
        })
      }

      editor.insertNode(mentionNode) // 插入 mention
      editor.move(searchValue.value.length) // 移动光标
    }
  }
  const onChange = editor => {
    const children = editor.children[editor.children.length - 1].children

    const paragraph = children[children.length - 1]
    if (
      paragraph.text &&
      paragraph.text.charAt(paragraph.text.length - 1) !== ' ' &&
      !paragraph.type &&
      paragraph.text.lastIndexOf('@') > -1
    ) {
      const lastAtIndex = paragraph.text.lastIndexOf('@')
      searchValue.value = paragraph.text.slice(lastAtIndex + 1)
      if (searchValue.value && searchValue.value.length < 10) {
        userList.value = staffListData.value.filter(
          item => item.fullName.toLowerCase().indexOf(searchValue.value) > -1
        )
        nextTick(() => {
          memberVisible.value = true
        })
      } else {
        userList.value = staffListData.value
        memberVisible.value = true
      }
    } else {
      memberVisible.value = false
    }
  }
  return {
    searchValue,
    memberVisible,
    onChange,
    userList,
    insertTagUser
  }
}
